package com.hyx.api.service.impl.pc_admin;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.hyx.api.domain.CustomerWithdraw;
import com.hyx.api.domain.FileUpload;
import com.hyx.api.domain.InquiryOrder;
import com.hyx.api.domain.RecycleOrder;
import com.hyx.api.domain.RecycleReceivingAddr;
import com.hyx.api.domain.RefundOrder;
import com.hyx.api.domain.SpreadOrder;
import com.hyx.api.domain.User;
import com.hyx.api.domain.VerifyModelOption;
import com.hyx.api.domain.bo.InquiryOrderBo;
import com.hyx.api.domain.bo.OfferOrderBo;
import com.hyx.api.domain.vo.InquiryOrderDetailVo;
import com.hyx.api.domain.vo.InquiryOrderVo;
import com.hyx.api.domain.vo.OfferOrderVo;
import com.hyx.api.domain.vo.RecycleOrderVo;
import com.hyx.api.domain.vo.RefundOrderVo;
import com.hyx.api.domain.vo.SpreadOrderVo;
import com.hyx.api.enums.OfferStatusEnum;
import com.hyx.api.mapper.CustomerWithdrawMapper;
import com.hyx.api.mapper.FileUploadMapper;
import com.hyx.api.mapper.InquiryOrderMapper;
import com.hyx.api.mapper.ModelMapper;
import com.hyx.api.mapper.OfferOrderMapper;
import com.hyx.api.mapper.RecycleOrderMapper;
import com.hyx.api.mapper.RecycleReceivingAddrMapper;
import com.hyx.api.mapper.RefundOrderMapper;
import com.hyx.api.mapper.SpreadOrderMapper;
import com.hyx.api.mapper.VerifyModelOptionMapper;
import com.hyx.api.service.pc_admin.IInquiryOrderService;
import com.hyx.api.utils.base.MobileBaseService;
import com.ruoyi.common.core.domain.AjaxResult;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 询价订单Service业务层处理
 *
 * @author HK
 * @date 2023-10-28
 */
@RequiredArgsConstructor
@Service
public class InquiryOrderServiceImpl implements IInquiryOrderService {
    private final InquiryOrderMapper inquiryOrderMapper;
    private final FileUploadMapper fileUploadMapper;
    private final VerifyModelOptionMapper verifyModelOptionMapper;
    private final FileUploadMapper uploadMapper;
    private final OfferOrderMapper offerOrderMapper;
    private final RefundOrderMapper refundOrderMapper;
    private final SpreadOrderMapper spreadOrderMapper;
    private final RecycleOrderMapper recycleOrderMapper;
    private final ModelMapper modelMapper;
    private final RecycleReceivingAddrMapper receivingAddrMapper;
    private final CustomerWithdrawMapper withdrawMapper;

    private final MobileBaseService mobileBaseService;

    /**
     * 查询询价订单
     *
     * @param id 询价订单主键
     * @return 询价订单
     */
    @Override
    public InquiryOrderVo selectInquiryOrderById(Long id) {
        InquiryOrderVo vo = inquiryOrderMapper.selectVoById(id);
        LambdaQueryWrapper<FileUpload> lqw = Wrappers.lambdaQuery();
        lqw.in(FileUpload::getId, Arrays.asList(vo.getFileIds().split(",")));
        List<FileUpload> files = fileUploadMapper.selectList(lqw);
        List<String> arr = new ArrayList<>();
        files.forEach(it -> {
            arr.add(it.getUrl());
        });
        vo.setFileUrls(arr);
        LambdaQueryWrapper<VerifyModelOption> lqw2 = Wrappers.lambdaQuery();
        lqw2.ne(VerifyModelOption::getParentId, 0);
        lqw2.eq(VerifyModelOption::getDelFlag, 0);
        lqw2.orderByAsc(VerifyModelOption::getType);
        lqw2.orderByAsc(VerifyModelOption::getSort);
        lqw2.in(VerifyModelOption::getId, Arrays.asList(vo.getVerifyModelIds().split(",")));
        List<VerifyModelOption> options = verifyModelOptionMapper.selectList(lqw2);
        StringBuilder str = new StringBuilder();
        options.forEach(it -> {
            str.append(it.getName()).append(" - ");
        });
        vo.setVerifyModelStrings(str.substring(0, str.length() - 3));
        //TODO 表以外的字段，写入vo
        return vo;
    }

    /**
     * 查询询价订单列表
     *
     * @param bo 询价订单
     * @return 询价订单
     */
    @Override
    public List<InquiryOrderVo> selectInquiryOrderList(InquiryOrderBo bo) {
        return inquiryOrderMapper.queryPageList(bo);
    }

    @Override
    public AjaxResult queryInquiryOrderDetailById(Long id, User user) {
        InquiryOrderDetailVo resDO = new InquiryOrderDetailVo();
        InquiryOrder inquiryOrder = inquiryOrderMapper.selectById(id);
        if (inquiryOrder == null) {
            return AjaxResult.error("没有该询价订单");
        }
        resDO.setId(inquiryOrder.getId());
        resDO.setModelVo(modelMapper.selectVoById(inquiryOrder.getModelId()));
        List<FileUpload> files = uploadMapper.selectBatchIds(Arrays.asList(inquiryOrder.getFileIds().split(",")));
        List<String> fileUrls = files.stream().map(FileUpload::getUrl).collect(Collectors.toList());
        resDO.setFileUrls(fileUrls);
        resDO.setRemark(inquiryOrder.getRemark());
        resDO.setModelName(inquiryOrder.getModelName());
        List<VerifyModelOption> modelOptions = verifyModelOptionMapper.selectBatchIds(Arrays.asList(inquiryOrder.getVerifyModelIds().split(",")));
        String specs = modelOptions.stream().filter(s -> s.getType() == 1).map(VerifyModelOption::getName).collect(Collectors.joining(","));
        resDO.setSpecs(specs);
        resDO.setVerifyOptionIds(modelOptions.stream().map(VerifyModelOption::getId).collect(Collectors.toList()));
        resDO.setRemark(inquiryOrder.getRemark());
        resDO.setOfferId(inquiryOrder.getOfferId());
        resDO.setUserId(inquiryOrder.getUserId());

        resDO.setIemi(inquiryOrder.getIemi());
        resDO.setCreateTime(inquiryOrder.getCreateTime());
        if (inquiryOrder.getOfferId() != null) {
            //回收订单处理
            resDO.setOfferOrderList(offerOrderMapper.queryOfferOrderVoList(new OfferOrderBo(), inquiryOrder.getOfferId(), mobileBaseService.getLoginUserId()));
            OfferOrderVo offerOrderVo = resDO.getOfferOrderList().get(0);
            LambdaQueryWrapper<RecycleReceivingAddr> receivingAddrWrapper = Wrappers.lambdaQuery();
            receivingAddrWrapper.eq(RecycleReceivingAddr::getRecycleBusId, offerOrderVo.getOfferBusId());
            RecycleReceivingAddr receivingAddr = receivingAddrMapper.selectOne(receivingAddrWrapper);
            if (receivingAddr != null) {
                offerOrderVo.setReceivingAddr(receivingAddr.getFullAddr());
                offerOrderVo.setReceivingName(receivingAddr.getContactName());
                offerOrderVo.setReceivingMobile(receivingAddr.getContactMobile());
            }
            LambdaQueryWrapper<RecycleOrder> recycleWrapper = Wrappers.lambdaQuery();
            recycleWrapper.eq(RecycleOrder::getInquiryOrderId, id);
            RecycleOrder order = recycleOrderMapper.selectOne(recycleWrapper);
            RecycleOrderVo recycleOrderVos = new RecycleOrderVo();
            if (ObjectUtils.isNotEmpty(order)) {
                BeanUtils.copyProperties(order, recycleOrderVos);
                if (receivingAddr != null) {
                    recycleOrderVos.setReceivingAddr(receivingAddr.getFullAddr());
                    recycleOrderVos.setReceivingName(receivingAddr.getContactName());
                    recycleOrderVos.setReceivingMobile(receivingAddr.getContactMobile());
                }
                resDO.setRecycleOrderVo(recycleOrderVos);
                LambdaQueryWrapper<RefundOrder> refundWrapper = Wrappers.lambdaQuery();
                refundWrapper.eq(RefundOrder::getRecycleOrderId, resDO.getRecycleOrderVo().getId());
                refundWrapper.orderByDesc(RefundOrder::getCreateTime);
                List<RefundOrderVo> refundOrderVos = refundOrderMapper.selectVoList(refundWrapper);
                if (!refundOrderVos.isEmpty()) {
                    resDO.getRecycleOrderVo().setRefundOrderVo(refundOrderVos);
                }
                LambdaQueryWrapper<SpreadOrder> spreadWrapper = Wrappers.lambdaQuery();
                spreadWrapper.eq(SpreadOrder::getRecycleOrderId, resDO.getRecycleOrderVo().getId());
                List<SpreadOrderVo> spreadOrderVos = spreadOrderMapper.selectVoList(spreadWrapper);
                if (!spreadOrderVos.isEmpty()) {
                    resDO.getRecycleOrderVo().setSpreadOrderVo(spreadOrderVos);
                }
                LambdaQueryWrapper<CustomerWithdraw> withdrawWrapper = Wrappers.lambdaQuery();
                withdrawWrapper.eq(CustomerWithdraw::getRecycleOrderId, recycleOrderVos.getId());
                CustomerWithdraw withdraw = withdrawMapper.selectOne(withdrawWrapper);
                if (withdraw != null) {
                    resDO.getRecycleOrderVo().setCustomerWithdraw(withdraw);
                }
            }
        } else {
            OfferOrderBo offerBo = new OfferOrderBo();
            offerBo.setInquiryOrderId(inquiryOrder.getId());
            if (null != user && user.getType() <= 1) {
                offerBo.setOfferBusId(user.getRecoveryId());
            }
            resDO.setOfferOrderList(offerOrderMapper.queryOfferOrderVoList(offerBo, null, mobileBaseService.getLoginUserId()));
        }
        return AjaxResult.success(resDO);
    }
}
